<template>
  <div class="main-box">
    <ContentWrap class="tree-box">
      <div class="btn-group">
        <el-button type="primary" @click="openDrawer('新增')">{{
          t('department.addDep')
        }}</el-button>
        <el-button type="primary" @click="openDrawerChildren('新增')">{{
          t('department.add')
        }}</el-button>
        <el-button type="primary" @click="exportXls">
          <Icon icon="uil:export" color="white" />&nbsp;{{ t('department.export') }}
        </el-button>
        <!-- <el-button type="primary"
          ><Icon icon="mdi:import" color="white" />&nbsp;{{ t('department.import') }}</el-button
        > -->
        <el-upload
          class="upload-demo"
          :http-request="importData"
          :show-file-list="false"
          accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        >
          <el-button type="primary">
            <Icon icon="mdi:import" color="white" />&nbsp;{{ t('department.import') }}
          </el-button>
        </el-upload>
        <el-button @click="del" :disabled="delStatus">{{ t('department.dels') }}</el-button>
      </div>
      <div class="choose">
        <el-icon color="#1890ff"> <InfoFilled /> </el-icon>当前选择：{{ chooseData.title }}
        <span @click="cancelChoose" v-if="chooseData.title">取消选择</span>
      </div>
      <el-input
        v-model="filterText"
        :placeholder="placeMsg(t('department.placeSearch'))"
        :suffix-icon="Search"
      />

      <el-tree
        ref="treeRef"
        class="filter-tree"
        node-key="key"
        show-checkbox
        :highlight-current="true"
        :expand-on-click-node="false"
        :data="treeData"
        :props="defaultProps"
        :check-strictly="selectObj.association"
        :default-expanded-keys="selectObj.expandedKeys"
        :default-checked-keys="selectObj.checkedKeys"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      />
      <el-divider />
      <el-select v-model="selectObj.selectVal" @change="selectChange" placeholder="树操作">
        <el-option
          v-for="item in selectOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </ContentWrap>
    <ContentWrap class="table-box">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基本信息" name="first">
          <el-empty v-if="chooseData.title == ''" description="请先选择一个部门!" />
          <el-form
            v-else
            ref="editFormRef"
            :model="editForm"
            status-icon
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="机构名称" prop="departName">
              <el-input
                v-model="editForm.departName"

                autocomplete="off"
                placeholder="请输入机构名称"
                maxlength="30"
              />
            </el-form-item>
            <el-form-item label="机构类别" prop="org_category">
              <!-- <el-input
                v-model="editForm.org_category"
                autocomplete="off"
                placeholder="请输入机构类别"
                maxlength="30"
              /> -->
              <el-select v-model="editForm.org_category">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                  v-for="(item, index) in orgCategoryOptions"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上级部门">
              <el-input
                v-model="editForm.parentName"

                disabled
                autocomplete="off"
                placeholder="请输入机构名称"
              />
            </el-form-item>
            <el-form-item label="排序值" prop="departOrder">
              <el-input-number v-model="editForm.departOrder" controls-position="right" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="editForm.mobile"

                maxlength="11"
                autocomplete="off"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="editForm.address"
                autocomplete="off"
                placeholder="请输入地址"
                maxlength="300"
              />
            </el-form-item>

            <el-form-item label="备注" prop="memo">
              <el-input
                v-model="editForm.memo"
                type="textarea"
                autocomplete="off"
                placeholder="请输入备注"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
            <el-divider />
            <div class="btn-all">
              <el-button @click="resetFormEdit(editFormRef)">重置</el-button>
              <el-button type="primary" @click="submitFormEdit(editFormRef)">保存</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>
    <Add ref="addForm" :passStatus="addStatus" @add-close="addClose" @add-send="addSend" />
  </div>
</template>

<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, onMounted, watch } from 'vue'
import { ElTree } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { vCheckVal } from '@/directives/checkVal'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartmentTreeListApi, removeDepart, editDepart } from '@/api/department/index'
import { Tree } from './interface'
import { uploadExcelApi, dictExportXlsAll, downXls } from '@/api/common/import'
import { selectOption } from '@/views/common'
import Add from './components/add.vue'
const { t } = useI18n()
const placeMsg = (text) => t('menuDetail.place') + text
const addForm = ref()
const delStatus = ref<boolean>(true)
const activeName = ref('first')
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref([]) // 左侧tree
const editFormRef = ref<FormInstance>()
const editForm = ref({
  address: '',
  departName: '',
  org_category: '',
  departOrder: 0,
  memo: '',
  mobile: '',
  id: 0,
  parentName: ''
})
// 机构类别下拉
const orgCategoryOptions = [
  { label: '市局', value: 1 },
  { label: '大队', value: 2 },
  { label: '中队', value: 3 },
]
let defaultEditfrom = ref({})
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入类型名称'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  // value: [{ required: false, validator: validatePass, trigger: 'blur' }],
  departName: [{ required: true, validator: validatePass2, trigger: 'blur' }],
  parentName: [{ required: false, trigger: 'blur' }],
  departOrder: [{ required: false, trigger: 'blur' }],
  address: [{ required: false, trigger: 'blur' }],
  memo: [{ required: false, trigger: 'blur' }],
  mobile: [
    {
      required: false,
      trigger: 'blur',
      message: '手机号格式不正确',
      pattern: /^((1[34578]\d{9}))$/
    }
  ]
})
//编辑提交
const submitFormEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log(editForm.value, 'editForm.value')
      let { code, message } = await editDepart(editForm.value)
      if (code == '200') {
        ElMessage({
          message: '保存成功',
          type: 'success'
        })
        getLoadTree()
      } else {
        ElMessage.error(message)
      }
      // console.log('submit!', result)
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const resetFormEdit = (formEl: FormInstance | undefined) => {
  // console.log('editForm.value', editForm.value)
  Object.keys(editForm.value).forEach((item) => {
    editForm.value[item] = defaultEditfrom.value[item]
  })
  // if (!formEl) return

  // formEl.resetFields()
}
//select 选项值selectVal
const selectObj = reactive({
  //select 值
  selectVal: '',
  //是否关联
  association: false,
  //展开
  expandedKeys: [],
  //选中
  checkedKeys: []
})
//选中之后的操作
const selectChange = () => {
  function setAllExpand(state) {
    var nodes = treeRef.value!.store.nodesMap
    for (var i in nodes) {
      nodes[i].expanded = state
    }
  }
  // console.log(selectObj.selectVal)
  switch (selectObj.selectVal) {
    case '1':
      //父子关联
      selectObj.association = false
      break
    case '2':
      //取消关联
      selectObj.association = true
      break
    case '3':
      //全部勾选
      // console.log(treeRef.value)
      treeRef.value!.setCheckedNodes(treeData.value)
      break
    case '4':
      //取消勾选
      treeRef.value!.setCheckedNodes([])
      break
    case '5':
      //展开所有
      setAllExpand(true)
      break
    case '6':
      //合并所有
      setAllExpand(false)
      break
    default:
      console.log(selectObj.selectVal)
  }
}
const chooseData = ref({
  title: '',
  row: {}
})
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const defaultProps = {
  children: 'children',
  label: 'title'
}
const defaultRightProps = {
  children: 'children',
  label: 'slotTitle'
}
// 获取部门tree
const getLoadTree = async () => {
  const { result } = await getDepartmentTreeListApi()
  treeData.value = result
}
// 过滤筛选tree
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.title.includes(value)
}

// 点击左侧tree
const handleNodeClick = (data: Tree) => {
  // console.log(data)
  defaultEditfrom.value = JSON.parse(JSON.stringify(data))
  chooseData.value.title = data.title
  chooseData.value.row = data

  //编辑赋值
  Object.keys(editForm.value).forEach((item) => {
    editForm.value[item] = data[item]
  })
  // console.log(editForm.value, 'editForm.value')
}
//左侧取消选择
const cancelChoose = () => {
  chooseData.value.title = ''
  treeRef.value?.setCurrentKey(null)
}
// 打开添加
let addStatus = ref<boolean>(false)
const openDrawer = () => {
  addStatus.value = true
  // console.log(addStatus.value, 'addStatus')
} // 接收add组件传值
const addClose = (payload) => {
  addStatus.value = payload
  // console.log(payload, 'payload', addStatus)
}
const addSend = (payload) => {
  addStatus.value = payload
  // console.log(payload, 'addSend')
  getLoadTree()
}
//选中左侧菜单触发时间
const handleCheckChange = (data: Tree, checked: boolean, indeterminate: boolean) => {
  // console.log(treeRef.value.getCheckedNodes())
  let checkedArr = treeRef.value.getCheckedNodes()
  if (checkedArr.length > 0) {
    delStatus.value = false
  } else {
    delStatus.value = true
  }
  // console.log(data, checked, indeterminate)
}
//新增子级菜单
const openDrawerChildren = () => {
  if (!chooseData.value.title) {
    ElMessage.error('请先点击选中上级部门！')
  } else {
    addForm.value.addChild(chooseData.value.row)
  }
}
//批量删除
const del = () => {
  let arr: any = []
  // @ts-expect-error
  let checkedArr = treeRef.value.getCheckedNodes()

  ElMessageBox.confirm(
    `确定要删除所选中的 ${checkedArr.length} 条数据，以及子节点数据吗?`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // ElMessage({
      //   type: 'success',
      //   message: 'Delete completed',
      // })
      checkedArr.map((item: any) => {
        arr.push(item.id)
      })
      let result = await removeDepart({ ids: arr.join(',') })
      // console.log(result, 'result')
      if (Number(result.code) == 200) {
        ElMessage({
          message: result.message,
          type: 'success'
        })
        getLoadTree()
      } else {
        ElMessage.error(result.message)
      }
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    })
}
//导出
const exportXls = async () => {
  let { result, code } = await dictExportXlsAll('/sys/depart/export', 'get', '', '')
  // console.log(result, 'result', code)
  if (code == 200) {
    downXls('', '', result)
    ElMessage({
      message: '下载成功',
      type: 'success'
    })
  } else {
    ElMessage.error('下载错误')
  }
}
// 导入
const importData = async ({ file }) => {
  let rst = await uploadExcelApi(file, '/sys/depart/importExcel')
  let { data } = rst
  if (data.code == 200 && data.success) {
    ElMessage.success('文件上传成功')
    getLoadTree()
  } else {
    ElMessage.error(`文件上传失败，${data.message}`)
  }
}
onMounted(() => {
  getLoadTree()
})
</script>

<style scoped>
@import './index.less';
</style>
